import { Effect, Reducer, Loading, history } from 'umi';
import qs from 'qs';
import services from '../service/demo';

/**
 * 组件connect时的props数据结构
 */

const DemoModel = {
  namespace: 'demojs',
  state: {
    list: [],
    detail: {},
    postResult: {},
  },
  effects: {
    /**
     * 获取项目列表
     * @param tools
     * @param call
     * @param put
     */
    *getList({}, { call, put, ssdr }) {
      const { status, data } = yield call(services.getList);
      if (status === 200) {
        yield put({
          type: 'updateState',
          payload: { list: data || [] },
        });
      }
    },
    /**
     * 根据列表项id获取项目详情
     * @param payload
     * @param call
     * @param put
     * @param tools
     */
    *getDetail({ payload }, { call, put }) {
      const { status, data } = yield call(services.getDetailById, payload);
      if (status === 200) {
        yield put({
          type: 'updateState',
          payload: { detail: data || {} },
        });
      }
    },
    /**
     * form表单提交并返回结果更新state
     * @param payload
     * @param call
     * @param put
     */
    *postForm({ payload }, { call, put }) {
      const { status, data } = yield call(
        services.postForm,
        qs.stringify(payload),
      );
      if (status === 200) {
        yield put({
          type: 'updateState',
          payload: { postResult: data || {} },
        });
        history.push(`/done`);
      }
    },
  },

  reducers: {
    updateState(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default DemoModel;
